package com.wb.mas.ui.auth;

import android.app.Application;
import android.net.Uri;
import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.wb.mas.R;
import com.wb.mas.app.Constants;
import com.wb.mas.app.SPKeys;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.ImageInfoEntity;
import com.wb.mas.entity.RootApiBean;
import com.wb.mas.entity.SubmitedAuthResponse;
import com.wb.mas.entity.UploadImageResponse;
import com.wb.mas.utils.response.ResultException;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthExtraViewModel extends AuthBaseViewModel {


    private static final String TAG = AuthExtraViewModel.class.getSimpleName();

    public class UiChangeEvent {
        public SingleLiveEvent takePhotoEvent = new SingleLiveEvent();
    }

    public UiChangeEvent uc = new UiChangeEvent();

    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> PassportBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> BaoxianBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> ShuikaBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> MingpianBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> CunzheBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> ChepaiBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> JiashizhengBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> GongzuoBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> XinyongkaBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> tempSelect = null;


    public AuthExtraViewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);
        setTitleText(getString(R.string.auth_extra_page_title));
    }


    @Override
    public void onCreate() {
        super.onCreate();

        getSubmitedInfo(Constants.AUTH_PAGE_CODE_ADDITIONAL_INFORMATION_CODE);

    }


    @Override
    protected void onSubmittedResponse(SubmitedAuthResponse response) {
        super.onSubmittedResponse(response);

        if (response == null || response.getData() == null || response.getData().getAdditionalInformation() == null)
            return;

        SubmitedAuthResponse.DataBean.AdditionalInformationBean additionalInformation = response.getData().getAdditionalInformation();
        List<SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean> imageList = additionalInformation.getImageList();
        for (int i = 0; i < imageList.size(); i++) {
            SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean imageListBean = imageList.get(i);
            if (Constants.FILE_TYPE_OF_5.equals(imageListBean.getFileType() + "")) {

                PassportBean.set(imageListBean);

            } else if (Constants.FILE_TYPE_OF_4.equals(imageListBean.getFileType() + "")) {

                BaoxianBean.set(imageListBean);
            } else if (Constants.FILE_TYPE_OF_3.equals(imageListBean.getFileType() + "")) {

                ShuikaBean.set(imageListBean);
            } else if (Constants.FILE_TYPE_OF_7.equals(imageListBean.getFileType() + "")) {

                MingpianBean.set(imageListBean);
            } else if (Constants.FILE_TYPE_OF_6.equals(imageListBean.getFileType() + "")) {

                CunzheBean.set(imageListBean);
            } else if (Constants.FILE_TYPE_OF_9.equals(imageListBean.getFileType() + "")) {

                ChepaiBean.set(imageListBean);
            } else if (Constants.FILE_TYPE_OF_8.equals(imageListBean.getFileType() + "")) {

                JiashizhengBean.set(imageListBean);
            } else if (Constants.FILE_TYPE_OF_12.equals(imageListBean.getFileType() + "")) {

                GongzuoBean.set(imageListBean);
            } else if (Constants.FILE_TYPE_OF_11.equals(imageListBean.getFileType() + "")) {

                XinyongkaBean.set(imageListBean);
            }
        }


    }

    public BindingCommand clickUploadPassport = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = PassportBean;
            uc.takePhotoEvent.setValue("");

        }
    });


    public BindingCommand clickUploadBaoxian = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = BaoxianBean;
            uc.takePhotoEvent.setValue("");


        }
    });
    public BindingCommand clickUploadShuika = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = ShuikaBean;
            uc.takePhotoEvent.setValue("");

        }
    });
    public BindingCommand clickUploadMingpian = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = MingpianBean;
            uc.takePhotoEvent.setValue("");


        }
    });
    public BindingCommand clickUploadCunzhe = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = CunzheBean;
            uc.takePhotoEvent.setValue("");


        }
    });
    public BindingCommand clickUploadChepai = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = ChepaiBean;
            uc.takePhotoEvent.setValue("");


        }
    });
    public BindingCommand clickUploadJiashizheng = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = JiashizhengBean;
            uc.takePhotoEvent.setValue("");


        }
    });
    public BindingCommand clickUploadGongzuo = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = GongzuoBean;
            uc.takePhotoEvent.setValue("");


        }
    });
    public BindingCommand clickUploadXinyongka = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempSelect = XinyongkaBean;
            uc.takePhotoEvent.setValue("");


        }
    });
    public BindingCommand onClickNextStep = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (!(PassportBean != null
                    && PassportBean.get() != null
                    && (!TextUtils.isEmpty(PassportBean.get().getLocalImgPath()) || !TextUtils.isEmpty(PassportBean.get().getImageUrl())))) {
                ToastUtils.showShort(getString(R.string.auth_upload_passport));
                return;

            }

            doUploadImgToServer();
        }
    });

    private void doUploadImgToServer() {

        showDialog();
        List<Observable<UploadImageResponse>> list = new ArrayList<>();
        if (PassportBean != null && PassportBean.get() != null && !TextUtils.isEmpty(PassportBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_5);
            list.add(model.uploadImage(params, new File(PassportBean.get().getLocalImgPath())));
        }

        if (BaoxianBean != null && BaoxianBean.get() != null && !TextUtils.isEmpty(BaoxianBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_4);
            list.add(model.uploadImage(params, new File(BaoxianBean.get().getLocalImgPath())));
        }
        if (ShuikaBean != null && ShuikaBean.get() != null && !TextUtils.isEmpty(ShuikaBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_3);
            list.add(model.uploadImage(params, new File(ShuikaBean.get().getLocalImgPath())));
        }

        if (MingpianBean != null && MingpianBean.get() != null && !TextUtils.isEmpty(MingpianBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_7);
            list.add(model.uploadImage(params, new File(MingpianBean.get().getLocalImgPath())));
        }

        if (CunzheBean != null && CunzheBean.get() != null && !TextUtils.isEmpty(CunzheBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_6);
            list.add(model.uploadImage(params, new File(CunzheBean.get().getLocalImgPath())));
        }

        if (ChepaiBean != null && ChepaiBean.get() != null && !TextUtils.isEmpty(ChepaiBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_9);
            list.add(model.uploadImage(params, new File(ChepaiBean.get().getLocalImgPath())));
        }
        if (JiashizhengBean != null && JiashizhengBean.get() != null && !TextUtils.isEmpty(JiashizhengBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_8);
            list.add(model.uploadImage(params, new File(JiashizhengBean.get().getLocalImgPath())));
        }

        if (GongzuoBean != null && GongzuoBean.get() != null && !TextUtils.isEmpty(GongzuoBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_12);
            list.add(model.uploadImage(params, new File(GongzuoBean.get().getLocalImgPath())));
        }

        if (XinyongkaBean != null && XinyongkaBean.get() != null && !TextUtils.isEmpty(XinyongkaBean.get().getLocalImgPath())) {
            Map<String, Object> params = new HashMap<>();
            params.put("fileType", Constants.FILE_TYPE_OF_11);
            list.add(model.uploadImage(params, new File(XinyongkaBean.get().getLocalImgPath())));
        }

        if (list.size() == 0) {
            dismissDialog();
            AuthJumpManager.jumpToNextPage(Constants.AUTH_PAGE_CODE_ADDITIONAL_INFORMATION_CODE);
            finish();
            return;
        }


        Observable.zip(list, new Function<Object[], Object>() {
            @Override
            public Object apply(Object[] objects) throws Exception {


                List<UploadImageResponse> imgsResponse = new ArrayList<>();

                for (int i = 0; i < objects.length; i++) {
                    imgsResponse.add((UploadImageResponse) objects[i]);
                }
                KLog.e(TAG, objects[0].getClass().getName());
                return imgsResponse;
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object object) throws Exception {
                        dismissDialog();


                        List<UploadImageResponse> responses = (List<UploadImageResponse>) object;
                        doUploadExtraInfo(responses);

                        KLog.i("upload img suc");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("upload fail:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });
    }

    /**
     * 上传 文本信息到服务器
     * <p>
     * <p>
     * {
     * "authPageCode": "additional_information_code",   //补充信息认证code
     * "imageList": [    // 补充信息的  这些都是上传图片返回的
     * {
     * "fileType": 6,
     * "imageName": "file",
     * "imagePath": "\/data1\/pic\/APP\/2019-04\/23\/file\/C9WUyDng.jpg",
     * "imageUrl": "http:\/\/47.92.143.84\/pic\/APP\/2019-04\/23\/file\/C9WUyDng.jpg"
     * },
     * {
     * "fileType": 8,
     * "imageName": "file",
     * "imagePath": "\/data1\/pic\/APP\/2019-04\/23\/file\/JSFh5hno.jpg",
     * "imageUrl": "http:\/\/47.92.143.84\/pic\/APP\/2019-04\/23\/file\/JSFh5hno.jpg"
     * }
     * ],
     * "channel": "1",
     * “isInformationWrong”:1   //如果是资料退回再次上传的 传1  要不是不传
     * "commonParam": 公参
     * "userUuid": "20190423953"
     * }
     *
     * @param responses
     */
    private void doUploadExtraInfo(List<UploadImageResponse> responses) {
        showDialog();
        Map<String, Object> params = new HashMap<>();
        params.put("authPageCode", Constants.AUTH_PAGE_CODE_ADDITIONAL_INFORMATION_CODE);
        if (SPUtils.getInstance().getBoolean(SPKeys.SP_ISBACK)) {
            params.put("isInformationWrong", "1");

        }
        List<ImageInfoEntity> infoList = new ArrayList<>();


        for (int i = 0; i < responses.size(); i++) {
            UploadImageResponse imageResponse = responses.get(i);
            infoList.add(imageResponse.getData().getImageInfo());
        }
        params.put("imageList", infoList);


        model.imageInformation(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RootApiBean>() {
                    @Override
                    public void accept(RootApiBean rootApiBean) throws Exception {

                        dismissDialog();
                        if (rootApiBean != null && rootApiBean.getStatus() == 200) {
                            AuthJumpManager.jumpToNextPage(Constants.AUTH_PAGE_CODE_ADDITIONAL_INFORMATION_CODE);
                            finish();

                        } else {
                            if (!TextUtils.isEmpty(rootApiBean.getMessage())) {
                                ToastUtils.showShort(rootApiBean.getMessage());
                            }
                        }
                        KLog.i("upload img suc");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("upload fail:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });
    }


    public void setImgPathToView(Uri mImageUri, File imageFile) {
        if (tempSelect != null && mImageUri != null) {
            SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean imageListBean = new SubmitedAuthResponse.DataBean.AdditionalInformationBean.ImageListBean();
//            imageListBean.setImagePath(imageFile.getAbsolutePath());
            imageListBean.localImgPath = imageFile.getAbsolutePath();
            tempSelect.set(imageListBean);
//            tempSelect.get().setImagePath(imageFile.getAbsolutePath());
        }
    }


}
